package com.jcl.recruit.core.web.context;

import com.jcl.recruit.core.web.utils.RequestConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Stack;

/**
 * @ClassName CurrentThreadContex
 * @Description TODO
 * @Author yyliu
 * @Date 2018/9/11 17:26
 * @Version 1.0
 **/
public class CurrentThreadContext {

    private static final Logger logger = LoggerFactory.getLogger(CurrentThreadContext.class);

    private static ThreadLocal<Stack<String>> currentAlias = new ThreadLocal<Stack<String>>();

    /* *
     * @Author yyliu
     * @Description //TODO 
     * @Date 18:17 2018/9/11
     * @Param []
     * @return void
     **/
    public static void backup(){
        Stack<String> aliasStack = getStack();
        if(aliasStack.size() < 1){
            return;
        }

        aliasStack.pop();
        logger.info("backup : {}", aliasStack.toString());
    }

    /* *
     * @Author yyliu
     * @Description //TODO
     * @Date 17:37 2018/9/11
     * @Param []
     * @return java.lang.String
     **/
    public static String getAlias(){
        Stack<String> aliasStack = getStack();
        if(aliasStack.size() < 1){
            return null;
        }
        return aliasStack.lastElement();
    }

    /* *
     * @Author yyliu
     * @Description //TODO 
     * @Date 17:34 2018/9/11
     * @Param [request]
     * @return void
     **/
    public static void setAlias(HttpServletRequest request){
        String alias = (String) request.getSession().getAttribute(RequestConstants.ATTR_CORP_CODE_KEY);
        setAlias(alias);
    }
    
    /* *
     * @Author yyliu
     * @Description //TODO 
     * @Date 17:32 2018/9/11
     * @Param [corpCode]
     * @return void
     **/
    public static void setAlias(String corpCode){
        Stack<String> aliasStack = getStack();
        aliasStack.clear();
        aliasStack.add(corpCode);
        logger.info("setAlias : {} ", corpCode);
    }
    
    /* *
     * @Author yyliu
     * @Description //TODO
     * @Date 17:29 2018/9/11
     * @Param []
     * @return java.util.Stack<java.lang.String>
     **/
    private static Stack<String> getStack(){

        Stack<String> aliasStack  = currentAlias.get();
        if(null == aliasStack){
            aliasStack = new Stack<>();
            currentAlias.set(aliasStack);
        }

        return aliasStack;
    }


}
